const Koa = require("koa");
const router = require("koa-router");
const jwt = require("jsonwebtoken");
const fs = require("fs");

// 读取公钥私钥
const PRIVATE_KEY = fs.readFileSync("./keys/private.key");
const PUBLIC_KEY = fs.readFileSync("./keys/public.key");

const app = new Koa();

const tokenRouter = new router();

// 登录接口
tokenRouter.post("/test", (ctx, next) => {
  const user = { id: 110, name: "why" };
  const token = jwt.sign(user, PRIVATE_KEY, {
    expiresIn: 10 * 1000, //10s*1000 过期
    algorithm: "RS256", // 默认不写的话是 hs265 对称加密 现在是非对称
  });

  ctx.body = token;
});

// 验证接口
tokenRouter.get("/demo", (ctx, next) => {
  let token = ctx.request.header.authorization;
  // console.log(token);
  token = token.replace("Bearer ", "");
  //   console.log(token);
  try {
    const res = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"],
    });
    ctx.body = res;
  } catch (error) {
    console.log(error.message);
    ctx.body = error.message;
  }
});

app.use(tokenRouter.routes());

app.listen(8001, () => {
  console.log("服务器");
});
